import { JwtService } from '@nestjs/jwt'
import { Injectable } from '@nestjs/common'
import { AdminLoginReq } from 'src/dtos/admin.dto'
import { assert } from 'src/utils'
import { Admin, IJwtPayload } from 'src/typings'
import { RepositoryService } from './repository.service'

@Injectable()
export class AdminService {

  private readonly repo: RepositoryService<Admin>

  constructor(
    private readonly jwtService: JwtService
  ) {
    this.repo = new RepositoryService('admin.json', 'username')
  }

  public login(dto: AdminLoginReq) {
    let model = this.repo.getAll().find(n => n.username === dto.username && n.password === dto.password)
    assert.throwBizError(model == null, '账号或密码错误')
    const payload: IJwtPayload = { username: model.username, type: 'admin' }
    return {
      access_token: this.jwtService.sign(payload)
    }
  }

}
